/** 
  课程新增
*/
<template>
    <div>
        <div class="project-application-container" style="height: 30px;">
            <el-breadcrumb style="float: left;" separator="/">
                <el-breadcrumb-item :to="{ path: '/courseManagementList' }">
                    <span @click="returnList">课程管理</span>
                </el-breadcrumb-item>
                <el-breadcrumb-item>
                    <span v-if="submitType === 'add'">创建课程</span>
                    <span v-else-if="submitType === 'edit'">编辑课程</span>
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <el-card
            v-loading="loading"
            element-loading-text="文件上传中"
            element-loading-spinner="el-icon-loading"
        >
            <span class="top-title">
                <el-button style="float:right" @click="returnList">返回</el-button>
                <h2 v-if="submitType === 'add'">创建课程</h2>
            </span>
            <hr />
            <el-form
                :model="proForm"
                :rules="rulesForm"
                ref="proForm"
                label-position="right"
                label-suffix="："
                label-width="100px"
            >
                <span class="topic-form-title">
                    <h3>基础信息</h3>
                </span>
                <br />
                <el-row :gutter="24">
                    <el-col :span="6">
                        <el-form-item label="课程名称" prop="title">
                            <el-input
                                v-model="proForm.title"
                                class="topic-input-select"
                                maxlength="32"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="开课学院" prop="college">
                            <el-select
                                v-model.trim="proForm.college"
                                style="width: 100%"
                                filterable
                            >
                                <el-option
                                    v-for="item in options.faculty"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="是否必修" prop="required">
                            <el-select v-model.trim="proForm.required" style="width: 100%">
                                <el-option
                                    v-for="item in isRequired"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <span class="topic-form-title">
                    <h3>课程基本资料上传</h3>
                </span>
                <br />
                <el-row :gutter="24">
                    <el-col :span="6">
                        <el-form-item label="封面图片" prop="cover" ref="cover">
                            <el-upload
                                action="/api/commonservice/obsfile/uploadfile"
                                list-type="picture-card"
                                :on-remove="handleAvatarRemove"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload"
                                :data="uploadConfig.data"
                                :on-exceed="handleExceed"
                                :on-error="handlerAvatarError"
                                :limit="1"
                                :file-list="fileListAvatar"
                            >
                                <i class="el-icon-plus"></i>
                            </el-upload>
                            <!-- <el-upload
                                class="avatar-uploader"
                                action="/api/commonservice/obsfile/uploadfile"
                                list-type="picture-card"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload"
                                :data="uploadConfig.data"
                                :on-remove="handleRemove"
                            >
                                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload> -->
                            <span class="el-upload__tip">
                                您可以上传.jpg、.png格式的文件，图片建议尺寸至少为264*168像素，文件体积大小不能超过2M
                            </span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="7">
                        <el-form-item label="课程材料" prop="materialList" ref="materialList">
                            <el-upload
                                class="upload-demo"
                                action="/api/commonservice/obsfile/uploadfile"
                                :on-remove="handleRemove"
                                :on-success="handlerUploadSuccess"
                                :before-remove="beforeRemove"
                                :before-upload="beforeUpload"
                                :on-error="handlerUploadError"
                                :data="uploadConfig.data"
                                multiple
                                :limit="1"
                                :on-exceed="handleExceed"
                                :file-list="fileList"
                                :on-preview="viewPdf"
                            >
                                <el-button size="small" type="primary">上传文件</el-button>
                                <div slot="tip" class="el-upload__tip">
                                    上传要求：只能1个文件(支持word\ppt\pdf格式)。
                                </div>
                                <div slot="tip" style="color:red">
                                    文档中的中文字体请使用宋体，否则容易出现中文乱码。
                                </div>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div>
                <hr />
                <div class="edu-opertion-bar">
                    <div class="float-right">
                        <el-button @click="returnList">取消</el-button>
                        <el-button type="primary" @click="onSubmit()">提交</el-button>
                    </div>
                </div>
            </div>
        </el-card>
    </div>
</template>

<script>
import courseManageApi from 'common/src/api/academicBehaviorNorms/lessonManage/courseManage'
import UTILS from 'common/src/utils/utils'
import { downloadfile } from 'common/src/api/upload'
import { queryDic } from 'common/src/api/dictionary'
import { downloadimage } from 'common/src/api/upload'
export default {
    props: {
        submitType: {
            type: String,
            default: ''
        },
        Id: {
            type: String,
            default: ''
        }
    },
    data() {
        let cannotEnter = (rule, value, callback) => {
            let reg = /[`$]/im
            if (reg.test(value)) {
                return callback(new Error(this.$t('identificationToDoList.cannotContain')))
            } else if (value === '') {
                return callback(new Error(this.$t('internship.pleaseEnter')))
            }
            return callback()
        }
        return {
            proForm: {
                college: '',
                required: '',
                title: '',
                cover: '',
                fileName: '',
                fileUrl: '',
                approvalStatus: '',
                postStatus: '',
                materialList: [],
                isAdministrator: 0,
                isFacultyStaff: 0,
                isTeacher: 0
            },
            loading: false,
            isTeacher: 0, // 教师
            isFacultyStaff: 0, // 教务员
            isAdministrator: 0, // 管理员
            fileListAvatar: [],
            auths: [],
            options: {
                faculty: []
            },
            isRequired: [{ label: '是', value: 1 }, { label: '否', value: 0 }],
            fileList: [],
            uploadConfig: {
                data: { bucketname: 'face', folderpath: 'file' }
            },
            rulesForm: {
                title: [{ required: true, validator: cannotEnter, trigger: 'blur' }], // 课程名称
                college: [{ required: true, message: '请选择', trigger: 'change' }], // 开课学院
                required: [{ required: true, message: '请选择', trigger: 'change' }], // 是否必修
                cover: [{ required: true, message: '请上传封面', trigger: 'change' }], // 封面图片
                materialList: [{ required: true, message: '请上传课程资料', trigger: 'change' }] // 课程材料
            }
        }
    },
    created() {
        let _this = this
        this.options.faculty = []
        if (localStorage.getItem('sessiondata')) {
            this.isTeacher = 0
            this.isFacultyStaff = 0
            this.isAdministrator = 0
            // 获取当前用户auths权限
            if (JSON.parse(localStorage.getItem('sessiondata')).auths) {
                this.auths = JSON.parse(localStorage.getItem('sessiondata')).auths
                if (this.auths) {
                    // this.auths.forEach(val => {
                    //     if (val.authCode === 'academic-tempSet-isTeacher') {
                    //         this.isTeacher = 1
                    //         this.getColleage()
                    //         debugger
                    //         return
                    //     } else if (val.authCode === 'academic-tempSet-isFacultyStaff') {
                    //         this.isFacultyStaff = 1
                    //         this.getColleage()
                    //         debugger
                    //         return
                    //     } else if (val.authCode === 'academic-tempSet-isAdministrator') {
                    //         this.isAdministrator = 1
                    //         _this.initOptions()
                    //         debugger
                    //         return
                    //     }
                    // })
                    if (JSON.parse(localStorage.getItem('sessiondata')).auths) {
                    this.auths = JSON.parse(localStorage.getItem('sessiondata')).auths
                    if (this.auths) {
                        for (let i = 0; i < _this.auths.length; i++) {
                            if (_this.auths[i].authCode === 'academic-tempSet-isAdministrator') {
                                this.isAdministrator = 1
                            } else if (_this.auths[i].authCode === 'academic-tempSet-isFacultyStaff') {
                                this.isFacultyStaff = 1
                            } else if (_this.auths[i].authCode === 'academic-tempSet-isTeacher') {
                                this.isTeacher = 1
                            }
                        }
                    }
                }
                    if(this.isAdministrator === 1) {
                        _this.initOptions()
                    } else if(this.isFacultyStaff === 1 || this.isTeacher === 1) {
                        _this.getColleage()
                    }
                }
            }
        }

        if (this.submitType === 'edit') {
            this.getDetail()
        }
    },

    methods: {
        returnList() {
            if (
                !this.proForm.title &&
                !this.proForm.college &&
                this.proForm.required !== 0 &&
                this.proForm.required !== 1 &&
                !this.proForm.cover &&
                !this.proForm.fileUrl
            ) {
                this.$emit('returnVal', 'list')
            } else {
                this.$confirm('取消将不会保存当前设置，是否确定?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$emit('returnVal', 'list')
                })
            }
        },
        async initOptions() {
            // 筛选条件字典查询
            let data = {
                lang: this.$store.getters.language || 'cn',
                type: 'allChild',
                keys: [
                    'X_YX' // 学院
                ]
            }
            await queryDic(data).then(res => {
                this.options.faculty.push({
                    label: '校级公共课',
                    value: '校级公共课'
                })
                for (let key in res.data.X_YX) {
                    this.options.faculty.push({
                        label: res.data.X_YX[key],
                        value: key
                    })
                }
            })
        },
        viewPdf() {
            downloadfile(this.proForm.fileUrl)
        },
        getDetail() {
            courseManageApi.getById(this.Id).then(res => {
                this.proForm.college = res.data.college
                this.proForm.title = res.data.title
                this.proForm.required = res.data.required
                this.proForm.approvalStatus = res.data.approvalStatus
                this.proForm.postStatus = res.data.postStatus
                this.proForm.cover = res.data.cover
                this.proForm.fileName = res.data.fileName
                this.proForm.fileUrl = res.data.fileUrl
                if (res.data.fileName) {
                    this.fileList.push({ name: res.data.fileName, fileId: res.data.fileUrl })
                    this.proForm.materialList.push({
                        fileName: res.data.fileName
                    })
                }

                if (res.data.cover) {
                    downloadimage(res.data.cover).then(resT => {
                        if (resT && resT.data) {
                            this.fileListAvatar.push({ url: resT.data.base })
                        }
                    })
                }
            })
        },
        onSubmit() {
            this.proForm.isTeacher = this.isTeacher
            this.proForm.isFacultyStaff = this.isFacultyStaff
            this.proForm.isAdministrator = this.isAdministrator
            this.$refs.proForm.validate(valid => {
                if (valid) {
                    if (this.submitType === 'edit') {
                        this.proForm.id = this.Id

                        courseManageApi.editCourse(this.proForm).then(res => {
                            this.$message({
                                message: '编辑成功',
                                type: 'success'
                            })
                            this.$emit('returnVal', 'list')
                        })
                    } else if (this.submitType === 'add') {
                        courseManageApi.addCourse(this.proForm).then(res => {
                            this.$message({
                                message: '新增成功',
                                type: 'success'
                            })
                            this.$emit('returnVal', 'list')
                        })
                    }
                }
            })
        },
        getColleage() {
            let parm = {
                isTeacher: this.isTeacher,
                isFacultyStaff: this.isFacultyStaff,
                isAdministrator: 0
            }
            courseManageApi.facultyList(parm).then(res => {
                if (res.code === 200) {
                    for (let key in res.data) {
                        this.options.faculty.push({ label: res.data[key], value: key })
                    }
                }
            })
        },
        handleRemove(file, fileList) {
            this.proForm.materialList = []
            this.fileList = []
            this.proForm.fileName = ''
            this.proForm.fileUrl = ''
        },
        handlerUploadError() {
            this.$message({
                message: this.$t('graduateBase.uploadFail'),
                type: 'error'
            })
            this.proForm.materialList = []
            this.loading = false
        },
        handlerUploadSuccess(response, file, fileList) {
            this.proForm.fileName = file.name
            this.proForm.fileUrl = response.data[file.name].objectkey
            this.proForm.materialList.push({
                fileName: file.name
            })
            this.$refs.materialList.clearValidate()
            this.loading = false
            this.$message({
                message: '上传成功',
                type: 'success'
            })
        },
        handleExceed(files, fileList) {
            this.$message.error('当前限制只能上传一个文件')
        },
        beforeUpload(file) {
            let fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
            let checkFileName = true
            if (file.name.indexOf('%') !== -1) {
                checkFileName = false
            } else if (file.name.indexOf('&') !== -1) {
                checkFileName = false
            } else if (file.name.indexOf('_') !== -1) {
                checkFileName = false
            } else if (file.name.indexOf('?') !== -1) {
                checkFileName = false
            }
            const uploadFlag =
                fileType === 'pdf' ||
                fileType === 'doc' ||
                fileType === 'docx' ||
                fileType === 'ppt' ||
                fileType === 'pptx'
            const isLt2M = file.size / 1024 / 1024 < 10

            if (!uploadFlag) {
                this.$message.error('请按要求上传文件!')
            }
            if (!isLt2M) {
                this.$message.error('上传文件大小不能超过 10MB!')
            }
            if (!checkFileName) {
                this.$message.error('课程材料名称包含特殊字符，请重命名后重新上传!')
            }
            if (uploadFlag && isLt2M && checkFileName) {
                this.loading = true
            }
            return uploadFlag && isLt2M && checkFileName
        },
        handleAvatarSuccess(res, file, fileList) {
            this.proForm.cover = res.data[file.name].objectkey
            this.$refs.cover.clearValidate()
        },
        handleAvatarRemove(file, fileList) {
            this.proForm.cover = ''
        },
        beforeAvatarUpload(file) {
            let fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
            const uploadFlag = fileType === 'jpg' || fileType === 'jpeg' || fileType === 'png'
            const isLt2M = file.size / 1024 / 1024 < 2

            if (!uploadFlag) {
                this.$message.error('请按要求上传图片!')
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!')
            }
            return uploadFlag && isLt2M
        }
    },
    handlerAvatarError() {
        this.$message({
            message: this.$t('graduateBase.uploadFail'),
            type: 'error'
        })
        this.proForm.cover = ''
    }
}
</script>
<style scoped lang="scss">
// .avatar-uploader .el-upload {
//     border: 1px dashed #d9d9d9;
//     border-radius: 6px;
//     cursor: pointer;
//     position: relative;
//     overflow: hidden;
// }
// .avatar-uploader .el-upload:hover {
//     border-color: #409eff;
// }
// .avatar-uploader-icon {
//     font-size: 28px;
//     color: #8c939d;
//     width: 148px;
//     height: 148px;
//     line-height: 148px;
//     text-align: center;
// }
// .avatar {
//     width: 148px;
//     height: 148px;
//     display: block;
// }
</style>
